﻿using BusinessLogic.Configuration;
using System;
using OpenPop.Mime;
using System.Collections.Generic;
using BusinessLogic.Messages;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Security;
using BusinessLogic.Messages;
using OfficeOpenXml;
using Common.Utils;

namespace TestApp
{
    class Program
    {
        static Base test = new Base();
        static void Main(string[] args)
        {
            string passOld = test.CompanyService.CreatePasswordHash("chaiko9.0");
            string pass = test.CompanyService.EncryPasswordHash(passOld);
            string a = pass;
            //Dictionary<int, Message> List = new Dictionary<int, Message>();
            //List<FileAttachment> seenUids = new List<FileAttachment>();
            //List<Message> newMessages = new List<Message>();
            //Receive(ref seenUids);
            //SaveToData(seenUids);
        }
        public static void Save(List<Result> List)
        {
            try
            {
                test.ResultsService.Save(List: List);
            }
            catch (Exception ex)
            {
                test.LogService.InsertLog(BusinessLogic.Audit.LogTypeEnum.Result, "Save Result", ex.Message);
            }
        }
        
        public static void Receive(ref List<FileAttachment> List)
        {
            string path = string.Format(@"{0}\{1}\{2}", PayrollConfig.appPath, "attachment", DateTime.Now.ToString("yyyy-MM-dd"));
            string FileName = "";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            List<string> seenUids = new List<string>();
            List<Message> newMessages = new List<Message>();
            newMessages = test.MessageService.FetchUnseenMessages("pop.gmail.com", 995, true, "joseph.toan99@gmail.com", "chaiko9.0", seenUids);
            foreach (var messages in newMessages)
            {
                List<MessagePart> attachments = messages.FindAllAttachments();
                foreach (MessagePart attachment in attachments)
                {
                    // Add the attachment to the list of attachments
                    //attachment.Save(attachment.FileName, attachment.Body);
                    string fileExten = attachment.FileName.EndsWith(".xls", StringComparison.Ordinal) ? ".xls" : (attachment.FileName.EndsWith(".xlsx", StringComparison.Ordinal) ? ".xlsx" : "");
                    switch (fileExten)
                    {
                        case ".xls":
                            FileName = string.Format(@"{0}\\{1}", path, attachment.FileName.Replace(".xls", ".xlsx"));
                            File.WriteAllBytes(FileName, attachment.Body);
                            break;
                        case ".xlsx":
                            FileName = string.Format(@"{0}\\{1}", path, attachment.FileName);
                            File.WriteAllBytes(FileName, attachment.Body);
                            break;
                    }
                    List.Add(new FileAttachment
                    {
                        FileName = FileName,
                        From = messages.Headers.From.MailAddress.Address,
                        To = "",
                        FromSender = messages.Headers.DateSent,
                        Subject = messages.Headers.Subject
                    });
                }
            }
        }
        public static void SaveToData(List<FileAttachment> filePath)
        {
            int endrow = 5;
            string DatePurchase = "";
            string PackageCode = "";
            DateTime ResDateReceive = DateTime.Now;
            List<Result> List = new List<Result>();
            foreach (var file in filePath)
            {
                string fileInfo = Path.GetDirectoryName(file.FileName) + "\\ template"  + Path.GetFileName(file.FileName);
                 
                var existingFile = new FileInfo(file.FileName);
                FileInfo filewrite = existingFile.CopyTo(fileInfo);

                using (var package = new ExcelPackage(filewrite))
                {
                    ExcelWorkbook workBook = package.Workbook;
                    if (workBook != null)
                    {
                        if (workBook.Worksheets.Count > 0)
                        {
                            ExcelWorksheet currentWorksheet = workBook.Worksheets.First();
                            while (true)
                            {
                                DatePurchase = CommonHelper.ToString(currentWorksheet.Cells[endrow, 2].Value);
                                if (DatePurchase.Length == 0)
                                {
                                    break;
                                }
                                PackageCode = CommonHelper.ToString(currentWorksheet.Cells[endrow, 9].Value);
                                List.Add(new Result
                                {
                                    PackageId = 0,
                                    PackageCode = PackageCode,
                                    DatePurchase = DatePurchase,
                                    CustomerId = 0,
                                    CustomerName = CommonHelper.ToString(currentWorksheet.Cells[endrow, 3].Value),
                                    TaxCode = CommonHelper.ToString(currentWorksheet.Cells[endrow, 4].Value),
                                    Address = CommonHelper.ToString(currentWorksheet.Cells[endrow, 5].Value),
                                    Mobile = CommonHelper.ToString(currentWorksheet.Cells[endrow, 6].Value),
                                    Email = CommonHelper.ToString(currentWorksheet.Cells[endrow, 7].Value),
                                    ServiceFree = CommonHelper.ToString(currentWorksheet.Cells[endrow, 10].Value),
                                    CustomerProfile = CommonHelper.ToString(currentWorksheet.Cells[endrow, 11].Value),
                                    ResDateReceive = ResDateReceive,
                                    ResConfirm = 3,
                                    ResFrom = file.From,
                                    ResTo = file.To,
                                    ResStatus = 1,
                                    Createby = 1,
                                    Modified = 1,
                                    CreateDate = ResDateReceive,
                                    ModifiedDate = ResDateReceive
                                });
                                endrow += 1;
                            }
                        }
                    }
                    endrow = 5;
                }
                if (File.Exists(fileInfo))
                {
                    File.Delete(fileInfo);
                }
            }
            if (List.Count > 0)
                Save(List);
        }
    }
}
